package com.sq.partner.manager.controller;

import java.sql.Struct;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.GatewayMenu;
import com.sq.partner.manager.mybatis.model.GatewayMenuUri;
import com.sq.partner.manager.mybatis.model.GatewayRoleMenu;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.TreeDto;
import com.sq.partner.manager.service.IGatewayMenuService;
import com.sq.partner.manager.service.IGatewayMenuUriService;
import com.sq.partner.manager.service.IGatewayRoleMenuService;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;

/**
 * 菜单Controller，
 * 1、显示菜单列表，控制不同用户根据不同权限显示不同菜单列表
 * 2、对菜单的增删改查
 * @author zhihuizhao
 *
 */
@Controller
@RequestMapping(value="/systemManager")
public class GatewayMenuController {
	private static Logger logger = LogUtil.getLog(GatewayMenuController.class);
	@Resource
	private IGatewayMenuService menuService;
	
	@Resource
	private IGatewayRoleMenuService rmService;
	@Resource
	private IGatewayMenuUriService muService;
	/**
	 * 展示菜单页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/menuManage")
	public String menuMgt(HttpServletRequest request) throws Exception
	{
		return "systemManager/menuManagement";
	}
	@RequestMapping(value="/style")
	public String style(HttpServletRequest request) throws Exception
	{
		return "systemManager/style";
	}
	

	/**
	 * 页面初始化查询当前用户角色下所有菜单
	 * @param request
	 * @param usercode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/menuManage/initMenuList")
	@ResponseBody
	public List<TreeDto> initAllMenus(HttpServletRequest request) throws Exception{
		HttpSession session = request.getSession();
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		List<GatewayMenu> list = menuService.getAllMenus(user.getUserid());
		String deptStr = user.getDepartmentStr();
		if(deptStr == null){
			deptStr = "00";
		}
		List<String>  deptList = Arrays.asList(deptStr.split(","));
		//判断用户所属机构是分公司还是总公司
		boolean headDept = false;
		for (String s : deptList) {
			if(s.startsWith("'00")){
				headDept = true;
				break;
			}
		}
		List<GatewayMenu> list2 = new ArrayList<GatewayMenu>();
		//如果不是总公司机构，不显示跟单费用配置菜单
		if(!headDept){
			for (GatewayMenu menu : list) {
				if("财险跟单费用配置".equals(menu.getMenuName()) || "意健险跟单费用配置".equals(menu.getMenuName())){
					list2.add(menu);
				}
			}
		}
		list.removeAll(list2);
		 List<TreeDto> resultList = new ArrayList<TreeDto>();
		 for(GatewayMenu od : list){
	            TreeDto td = new TreeDto();
	            td.setName(od.getMenuName());
	            td.setId(String.valueOf(od.getMenuid()));
	            td.setpId(String.valueOf(od.getParentMenuId()));
	            if(StrUtil.isEmpty(od.getUrl())){
	            	td.setUrl(od.getUrl());
	            }else{
	            	String path = request.getContextPath();
	            	td.setUrl(path+od.getUrl());
	            }
	            td.setTarget("main");
	            resultList.add(td);
		 }
		return resultList;
	}
	
	
	
	/**
	 * 此方法为用户在新增/编辑菜单窗口初始化时查询所有菜单，没有超链接
	 * 在打开编辑菜单窗口时，会把当前菜单ID传入后台，使查询结果中不含该菜单本身，没有权限关联
	 * 在打开新增菜单窗口时，则不传入任何参数，直接查询库中所有菜单，没有权限关联
	 * @param request
	 * @param menuid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/menuManage/selectParentMenu")
	@ResponseBody
	public List<TreeDto> initMenus(HttpServletRequest request,Long menuid) throws Exception{
		HttpSession session = request.getSession();
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		List<GatewayMenu> list = new ArrayList<GatewayMenu>();
		if(menuid!=null){
			list = menuService.getAllMenusExceptSelf(menuid);
		}else{
			Map<String, Object> map = null;
			list = menuService.queryAllMenuIsAsParentMenu(map);
		}
		 List<TreeDto> menuList = new ArrayList<TreeDto>();
		 for(GatewayMenu od : list){
	            TreeDto td = new TreeDto();
	            td.setName(od.getMenuName());
	            td.setId(String.valueOf(od.getMenuid()));
	            td.setpId(String.valueOf(od.getParentMenuId()));
	            if(od.getIfLastMenu() == (long)1){
	            	td.setNocheck(true);
	            }else{
	            	td.setNocheck(false);
	            }
	            menuList.add(td);
		 }
		return menuList;
	}
	
	
	/**
	 * 此方法为角色管理页面，配置菜单窗口中的树形菜单展示
	 * @param request
	 * @param menuid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/menuManage/selectMenusToRole")
	@ResponseBody
	public List<TreeDto> getMenus(HttpServletRequest request,Long menuid) throws Exception{
		HttpSession session = request.getSession();
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		List<GatewayMenu> list = new ArrayList<GatewayMenu>();
		if(menuid!=null){
			list = menuService.getAllMenusExceptSelf(menuid);
		}else{
			
			Map<String, Object> map = new HashMap<String,Object>();
			if((user.getDepartmentStr().contains(Constants.HQ_BRANCH_CODE))){
				list = menuService.queryAllMenuIsAsParentMenu(null);
			}else{
				map.put("menuType", "1");
				list = menuService.queryAllMenuIsAsParentMenu(map);
			}
		}
		 List<TreeDto> menuList = new ArrayList<TreeDto>();
		 for(GatewayMenu od : list){
	            TreeDto td = new TreeDto();
	            td.setName(od.getMenuName());
	            td.setId(String.valueOf(od.getMenuid()));
	            td.setpId(String.valueOf(od.getParentMenuId()));
	            menuList.add(td);
		 }
		return menuList;
	}
	
	/**
	 * 菜单主页面，查询所有菜单信息列表
	 * @param pageIndex
	 * @param menu
	 * @param menuName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/menuManage/initAllMenus")
	public @ResponseBody Page queryAllMenus(Integer pageIndex,GatewayMenu menu,String menuName) throws Exception{
		
		if(StrUtil.isNotEmpty(menuName)){
			menu.setMenuName(menuName);
		}
		Page p = new Page();
		p.setCurrent(pageIndex);
		Page page = menuService.queryPage(p, pageIndex, menu);
		return page;
	}

	
	/**
	 * 添加菜单
	 * @param menu
	 * @param menuName
	 * @param parentMenuId
	 * @param sortNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/menuManage/addMenu")
	public @ResponseBody Result addNewMenu(HttpServletRequest req,GatewayMenu menu,String menuName,Long parentMenuId,Long sortNo,String url,String menuDesc,String menuType) throws Exception {
		if(StrUtil.isNotEmpty(menuName)){
			menu.setMenuName(menuName);
			logger.info("上级菜单ID---------------------------"+parentMenuId);
			if(parentMenuId==null){
				parentMenuId=(long)0;
			}
			menu.setParentMenuId(parentMenuId);
			menu.setSortNo(sortNo);
			menu.setUrl(url);
			//如果没有url输入，则默认该菜单非末节点菜单，否则，该菜单即末节点菜单
			if(StrUtil.isEmpty(url)){
				menu.setIfLastMenu((long)2);
			}else{
				menu.setIfLastMenu((long)1);
			}
			menu.setMenuDesc(menuDesc);
			menu.setOperTime(getCurdate());
			menu.setMenuType(menuType);
			GatewayUser u = getSessionUser(req);
			menu.setOperUser(u.getUserid());
			boolean flag = menuService.addMenu(menu);
			if(flag){
				logger.info("添加菜单成功");
				return Result.success("添加成功");
			}else{
				logger.info("添加菜单失败");
				return Result.fail("添加失败");
			}
		}else{
			return Result.fail("菜单名称不能为空");
		}
	}
	

	
	/**
	 * 编辑菜单
	 * @param req
	 * @param menu
	 * @param menuName
	 * @param parentMenuId
	 * @param sortNo
	 * @param url
	 * @param menuDesc
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/menuManage/modifyMenu")
	public @ResponseBody Result modifyMenuByID(HttpServletRequest req,GatewayMenu menu,Long menuid,String menuName,Long parentMenuId,Long sortNo,String url,String menuDesc,String menuType) throws Exception{
		if(StrUtil.isNotEmpty(menuName)){
			if(menuid==null){
				menuid = (long)-1;
			}
			menu.setMenuid(menuid);
			menu.setMenuName(menuName);
			logger.info("上级菜单ID---------------------------"+parentMenuId);
			if(parentMenuId==null){
				parentMenuId=(long)0;
			}
			menu.setParentMenuId(parentMenuId);
			menu.setSortNo(sortNo);
			menu.setUrl(url);
			//如果没有url输入，则默认该菜单非末节点菜单，否则，该菜单即末节点菜单
			if(StrUtil.isEmpty(url)){
				menu.setIfLastMenu((long)2);
			}else{
				menu.setIfLastMenu((long)1);
			}
			menu.setMenuDesc(menuDesc);
			menu.setOperTime(getCurdate());
			menu.setMenuType(menuType);
			GatewayUser u = getSessionUser(req);
			menu.setOperUser(u.getUserid());
			boolean flag = menuService.modifyMenu(menu);
			if(flag){
				logger.info("编辑菜单成功");
				return Result.success("修改成功");
			}else{
				logger.info("编辑菜单失败");
				return Result.error("修改失败");
			}
		}else{
			return Result.fail("菜单名称不能为空");
		}
	}
	
	/**
	 * 删除菜单，如果该菜单有子菜单，提示用户不能删除，如果没有则允许删除
	 * @param menuid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/menuManage/deleteMenu")
	public @ResponseBody Result deleteMenuById(GatewayRoleMenu rm,Long parentMenuid) throws Exception{
		if(parentMenuid!=null){
			List<GatewayMenu> list = menuService.queryChildMenuIsExists(parentMenuid);
			logger.info("子菜单集合------------------------------------------------"+list.size());
			if(list.size()==0){
				//删除之前，先从角色菜单表删掉相关记录
				//删除菜单表记录
				rmService.delRoleMenusForMenu(parentMenuid);
				boolean flag = menuService.deleteMenu(parentMenuid);
				if(flag){
					logger.info("删除成功");
					return Result.success("删除成功");
				}else{
					logger.info("删除失败");
					return Result.error("删除失败");
				}
			}else{
				return Result.error("该菜单下有子菜单，不能删除");
			}
		}else{
			return Result.error("系统无法找到要删除的菜单");
		}
	}
	
	/**
	 * 查询某个菜单信息
	 * @param menu
	 * @param menuid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/menuManage/queryMenuInfo")
	public @ResponseBody String getMenuInfoByMenuId(GatewayMenu menu, Long menuid) throws Exception{
		menu = menuService.queryMenuInfo(menuid);
		String menuStr = JsonUtils.toJson(menu);
		return menuStr;
	}
	
	
	/**
	 * 查询某个菜单下所有uri配置
	 * @param menuId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/menuManage/loadMenuUri")
	public @ResponseBody List<GatewayMenuUri> loadMenuUri(Long menuId) throws Exception{
		List<GatewayMenuUri> list = muService.queryMenuUriByMenuid(menuId);
		return list;
	} 	
	
	
	/**
	 * 新增菜单Uri
	 * @param req
	 * @param menuUri
	 * @param menuid
	 * @param uri
	 * @param uriDesc
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/menuManage/addNewMenuUri")
	public @ResponseBody Result addMenuUri(HttpServletRequest req,GatewayMenuUri menuUri,Long menuid,String uri,String uriDesc) throws Exception{
		if(StrUtil.isNotEmpty(uri)){
			GatewayUser u = getSessionUser(req);
			menuUri.setOperUser(u.getUserid());
			menuUri.setOperTime(getCurdate());
			menuUri.setUri(uri);
			menuUri.setUriDesc(uriDesc);
			menuUri.setMenuId(menuid); 
			boolean flag = muService.addMenuUri(menuUri);
			if(flag){
				return Result.success("新增菜单Uri成功");
			}else{
				return Result.error("新增菜单Uri失败");
			}
		}else{
			if(StrUtil.isEmpty(uri)){
				return Result.error("uri不能为空");
			}
		}
		return null;
	}
	
	
	/**
	 * 删除uri
	 * @param menuUri
	 * @param uriId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/menuManage/delMenuUri")
	public @ResponseBody Result delmenuUri(GatewayMenuUri menuUri,Long uriId) throws Exception{
		if(null!=uriId){
			boolean flag = muService.delMenuUri(uriId);
			if(flag){
				return Result.success("删除成功");
			}else{
				return Result.error("删除失败");
			}
		}else{
			return Result.error("无法获取该记录的Id，不能进行删除操作");
		}
	}
	
	
	/**
	 * 修改uri
	 * @param req
	 * @param menuUri
	 * @param uriId
	 * @param uriStr
	 * @param uridescStr
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/menuManage/updateMenuUri")
	public @ResponseBody Result updateMenuUri(HttpServletRequest req,GatewayMenuUri menuUri,Long uriId,String uriStr,String uridescStr) throws Exception{
		if(null!=uriId){
			menuUri.setUriId(uriId);
			menuUri.setUri(uriStr);
			menuUri.setUriDesc(uridescStr);
			menuUri.setOperTime(getCurdate());
			menuUri.setOperUser(getSessionUser(req).getUserid());
			
			boolean flag = muService.updateMenuUri(menuUri);
			if(flag){
				return Result.success("修改成功");
			}else{
				return Result.error("修改失败");
			}
		}else{
			return Result.error("无法获取该记录ID，不能进行修改操作");
		}
	}
	/**
	 * 获取系统当前时间
	 * @return
	 * @throws Exception
	 */
	public static Date getCurdate() throws Exception{
		Date dt = new Date();
		return dt;
	}
	
	/**
	 * 获取session中的User
	 * @param req
	 * @return
	 */
	public static GatewayUser getSessionUser(HttpServletRequest req){
		HttpSession session = req.getSession();
		GatewayUser u = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		return u;
	}

}
